const express = require('express');
const router = express.Router();
const createError = require('http-errors');
const sequelize = require('../config/database');
const Product = require('../models/Product');
const Supplier = require('../models/Supplier');
const Category = require('../models/Category');
const Sale = require('../models/Sale');
const Purchase = require('../models/Purchase');
const { Op } = require('sequelize');

// 创建商品
router.post('/createProduct', async (req, res, next) => {
  try {
    const { name, purchasePrice, supplierId, stock, category } = req.body;

    if (!name || !purchasePrice || !supplierId || !stock) {
      return res.status(400).json({
        message: '缺少必要参数'
      });
    }

    // 处理分类
    let categoryId = null;
    if (category) {
      // 查找是否已存在相同名称的分类
      let categoryRecord = await Category.findOne({
        where: { name: category }
      });

      // 如果不存在，则创建新分类
      if (!categoryRecord) {
        categoryRecord = await Category.create({ name: category });
      }

      categoryId = categoryRecord.id;
    }

    // 查找是否存在同名商品
    let product = await Product.findOne({
      where: {
        name,
        supplierId // 同一个供应商下的同名商品
      }
    });

    if (product) {
      // 如果存在，更新库存
      await product.update({
        stock: sequelize.literal(`stock + ${stock}`), // 使用 sequelize.literal 进行数值计算
        purchasePrice // 更新最新进价
      });
    } else {
      // 如果不存在，创建新商品
      product = await Product.create({
        name,
        purchasePrice,
        supplierId,
        stock: stock || 0,
        categoryId
      });
    }

    // 创建进货记录
    const purchase = await Purchase.create({
      productId: product.id,
      quantity: stock,
      price: purchasePrice,
      total: purchasePrice * stock
    });

    res.json({
      product,
      purchase
    });
  } catch (error) {
    next(error);
  }
});

// 获取商品列表
router.get('/getProductList', async (req, res, next) => {
  try {
    const { page, size, offset } = req.getPaginationParams();
    const { name, supplierId, categoryId } = req.query;

    const where = {};
    if (name) where.name = name;
    if (supplierId) where.supplierId = supplierId;
    if (categoryId) where.categoryId = categoryId;

    const { count, rows } = await Product.findAndCountAll({
      where,
      include: [
        {
          model: Supplier,
          as: 'supplier',
          attributes: ['name']
        },
        {
          model: Category,
          as: 'category',
          attributes: ['name']
        }
      ],
      offset,
      limit: size,
      order: [['createdAt', 'DESC']]
    });

    res.paginate(rows, {
      total: count,
      page,
      size
    });
  } catch (error) {
    next(error);
  }
});

// 获取所有分类
router.get('/categories', async (req, res, next) => {
  try {
    const categories = await Category.findAll({
      order: [['name', 'ASC']]
    });

    res.json(categories);
  } catch (error) {
    next(error);
  }
});

// 获取单个商品
router.get('/:id', async (req, res, next) => {
  try {
    const product = await Product.findByPk(req.params.id, {
      include: [{
        model: Supplier,
        as: 'supplier',
        attributes: ['name']
      },
      {
        model: Category,
        as: 'category',
        attributes: ['name']
      }]
    });

    if (!product) {
      throw createError(404, '商品不存在');
    }

    res.json(product);
  } catch (error) {
    next(error);
  }
});

// 更新商品
router.put('/:id', async (req, res, next) => {
  try {
    const { name, purchasePrice, salePrice, supplierId, warningStock } = req.body;
    const product = await Product.findByPk(req.params.id);

    if (!product) {
      throw createError(404, '商品不存在');
    }

    await product.update({
      name,
      purchasePrice,
      salePrice,
      supplierId,
      warningStock
    });

    res.json(product);
  } catch (error) {
    next(error);
  }
});

// 删除商品
router.delete('/:id', async (req, res, next) => {
  try {
    const product = await Product.findByPk(req.params.id);
    if (!product) {
      throw createError(404, '商品不存在');
    }

    await product.destroy();
    res.json({ message: '删除成功' });
  } catch (error) {
    next(error);
  }
});

// 商品销售
router.post('/:id/sell', async (req, res, next) => {
  try {
    const { quantity, price } = req.body;
    const productId = req.params.id;

    const product = await Product.findByPk(productId);
    if (!product) {
      throw createError(404, '商品不存在');
    }

    if (product.stock < quantity) {
      res.status(400).json({
        message: '库存不足'
      });
    }

    // 创建销售记录
    const sale = await Sale.create({
      productId,
      quantity,
      price: price,
      total: price * quantity
    });

    // 更新库存
    await product.update({
      stock: product.stock - quantity
    });

    res.json(sale);
  } catch (error) {
    next(error);
  }
});

// 商品进货
router.post('/:id/purchase', async (req, res, next) => {
  try {
    const { quantity, name, purchasePrice, supplierId, warningStock, stock } = req.body;

    // 验证必要参数
    if (!name || !purchasePrice || !supplierId || !quantity || !stock) {
      return res.status(400).json({
        message: '缺少必要参数'
      });
    }

    // 创建新商品
    const product = await Product.create({
      name,
      purchasePrice,
      supplierId,
      stock: stock,
      warningStock: warningStock || 10
    });

    // 创建进货记录
    const purchase = await Purchase.create({
      productId: product.id,
      quantity,
      price: purchasePrice,
      total: purchasePrice * quantity
    });

    res.json({
      purchase,
      product
    });
  } catch (error) {
    next(error);
  }
});

module.exports = router;
